package com.zhijian.medical.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.zhijian.medical.annotation.Response;
import com.zhijian.medical.entity.po.Message;
import com.zhijian.medical.entity.po.Person;
import com.zhijian.medical.entity.vo.request.EmailSendSaveOrUpdateVo;
import com.zhijian.medical.entity.vo.request.EmailSendSearchVo;
import com.zhijian.medical.entity.vo.response.EmailSendVo;
import com.zhijian.medical.holder.CurrentUserHolder;
import com.zhijian.medical.service.EmailSendService;
import com.zhijian.medical.service.MessageService;
import com.zhijian.medical.service.PersonService;
import com.zhijian.medical.util.Page;
import com.zhijian.medical.util.SendEmailUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 发送邮件 控制层
 *
 * @author auto
 * @version 1.0
 * @date 2023-12-27 20:31:03
 */
@Slf4j
@Controller
@Api(tags = "发送邮件")
public class EmailSendController {

    @Autowired
    private EmailSendService service;

    @Autowired
    private MessageService messageService;

    @Autowired
    private PersonService personService;

    /**
     * 新增
     *
     * @param param
     * @return
     */
    @Response
    @PostMapping("/email/send")
    @ApiOperation("新增")
    public boolean insert(@RequestBody EmailSendSaveOrUpdateVo param) {
        param.setCreateUserId(CurrentUserHolder.getUser().getId());
        log.info("{} - {}| insert info", this.getClass().getSimpleName(), param);
        return service.save(param);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Response
    @DeleteMapping("/email/send/{id}")
    @ApiOperation("删除")
    public boolean delete(@PathVariable("id") Long id) {
        log.info("{} - {}| delete info", this.getClass().getSimpleName(), id);
        service.deleteById(id);
        return true;
    }

    /**
     * 修改
     *
     * @param id
     * @param param
     * @return
     */
    @Response
    @PutMapping("/email/send/{id}")
    @ApiOperation("修改")
    public boolean update(@PathVariable("id") Long id, @RequestBody EmailSendSaveOrUpdateVo param) {
        log.info("{} - {}| update info, {}", this.getClass().getSimpleName(), id, param);
        param.setId(id);
        return service.modify(param);
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @Response
    @GetMapping("/email/send/{id}")
    @ApiOperation("根据id查询")
    public EmailSendVo selectById(@PathVariable("id") Long id) {
        log.info("{} - {}| query info", this.getClass().getSimpleName(), id);
        return service.selectVoById(id);
    }

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @Response
    @PostMapping("/email/send/page")
    @ApiOperation("分页查询")
    public Page<EmailSendVo> selectByCondition(@RequestBody(required = false) EmailSendSearchVo param) {
        if (param == null)
            param = EmailSendSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        return service.selectPage(param);
    }

    /**
     * 列表查询
     *
     * @param param
     * @return
     */
    @Response
    @PostMapping("/email/send/list")
    @ApiOperation("列表查询")
    public List<EmailSendVo> selectList(@RequestBody(required = false) EmailSendSearchVo param) {
        if (param == null)
            param = EmailSendSearchVo.builder().build();
        log.info("{} - {}| query info", this.getClass().getSimpleName(), param);
        return service.selectList(param);
    }

    /**
     * 批量删除
     *
     * @param idList
     * @return
     */
    @Response
    @DeleteMapping("/email/send/list")
    @ApiOperation("批量删除")
    public boolean delete(@RequestBody(required = false) List<Long> idList) {
        log.info("{} - {}| delete info", this.getClass().getSimpleName(), idList);
        service.deleteByIdList(idList);
        return true;
    }

    /**
     * 发送
     *
     * @param id
     * @return
     */
    @Response
    @PostMapping("/email/send/do/{id}")
    @ApiOperation("发送")
    public boolean send(@PathVariable("id") Long id) {
        return service.send(id);
    }

    @Response
    @GetMapping("/email/send/fix")
    @ApiOperation("发送")
    public boolean fix() {
        List<Message> messages = messageService.selectEmailFixList();
        if (CollectionUtil.isNotEmpty(messages)) {
            for (Message message : messages) {
                Long receiveUserId = message.getReceiveUserId();
                Person person = personService.selectById(receiveUserId);

                String result = "";
                if (Objects.nonNull(person)) {
                    String email = person.getEmail();
                    if (StringUtils.isNotBlank(email)) {
                        try {
                            SendEmailUtil.sendEmail(email, message.getTitle(), message.getContent());
                            result = "ok";
                        } catch (Exception e) {
                            e.printStackTrace();
                            result = String.format("fail，原因：%s", e);
                        }
                    } else {
                        result = "fail，原因：用户未输入邮箱";
                    }
                    System.out.println(person.getName()+" 发送完毕，结果："+result);
                }

                messageService.updateByPrimaryKeySelective(Message.builder()
                        .id(message.getId())
                        .result(result)
                        .build());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
        return true;
    }

}